Scientific Computing with Python by Claus Führer

Scientific Computing with Python by Claus Führer

Author:Claus Führer
Language: eng
Format: mobi, epub
Tags: COM062000 - COMPUTERS / Data Modeling and Design, COM051360 - COMPUTERS / Programming Languages / Python, COM018000 - COMPUTERS / Data Processing
Publisher: Packt Publishing
Published: 2021-06-21T04:33:31+00:00


8.4.2 Class methods

We saw in Section 8.3: Bound and unbound methods how methods are either bound to an instance of a class or remain in a state as unbound methods. Class methods are different. They are always bound methods. They are bound to the class itself.

We will first describe the syntactic details and then give some examples to show what these methods can be used for.

To indicate that a method is a class method, the decorator line precedes the method definition:

@classmethod

While standard methods make a reference to an instance by the use of their first argument, the first argument of a class method refers to the class itself. By convention, the first argument is called self for standard methods and cls for class methods.

The following is an example of the standard case:

class A: def func(self,*args): <...>

This is contrasted by an example of the classmethod case:

class B: @classmethod def func(cls,*args): <...>

In practice, class methods may be useful for executing commands before an instance is created, for instance, in a preprocessing step. See the following example.

In this example, we show how class methods can be used to prepare data before creating an instance:

class Polynomial: def __init__(self, coeff): self.coeff = array(coeff) @classmethod def by_points(cls, x, y): degree = x.shape[0] - 1 coeff = polyfit(x, y, degree) return cls(coeff) def __eq__(self, other): return allclose(self.coeff, other.coeff)

The class is designed so that a polynomial object is created by specifying its coefficients. Alternatively, the class method by_points allows us to define a polynomial by interpolation points.

We can transform the interpolation data to the polynomial coefficients even when no instance of Polynomial is available:

p1 = Polynomial.by_points(array([0., 1.]), array([0., 1.])) p2 = Polynomial([1., 0.]) print(p1 == p2) # prints True

Another example of a class method is presented in Section 8.7: Classes as decorators. There, a class method is used to access information related to several (or all) instances from this class.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.